package com.ruihang.generalibrary.utils;

/**
 * 数据版本类，用于缓存记录本地数据的更改版本
 * Created by Administrator on 2017/4/24.
 */

public class DatasVersion {
    private int key;
    private int version;
    private Object syncObj=new Object();

    public DatasVersion(int key, int version) {
        this.key = key;
        this.version = version;
    }

    public DatasVersion(int key) {
        this.key = key;
        this.version=1;
    }

    public boolean isVersionDiff(int version){
        synchronized (syncObj){
            return version!=this.version;
        }
    }

    /**
     *
     * @return 更新后的version
     */
    public int updateVersion(){
        synchronized (syncObj){
            version++;
            return version;
        }
    }

    public int updateVersion(int upCount){
        synchronized (syncObj){
            if (upCount>0){
                int n=Integer.MAX_VALUE-version-upCount;
                if (n>=0){
                    version+=upCount;
                }else {
                    version=-n;
                }
            }
            return version;
        }
    }

    public int getVersion() {
        synchronized (syncObj) {
            return version;
        }
    }

    public int getKey() {
        return key;
    }
}
